<?php
declare(strict_types=1);

namespace Service\DeclareService\PayDeclareCompany;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Order;
use Service\VenderClient\PayCenterApi\HnapayApiClient;
use App\Model\BbcModel\OrderReportLog;
use App\Model\BbcModel\PayReport;
use App\Model\BbcModel\OrderReportStatus;
use Service\MessageService\PayNotifyService;
use Service\DeclareService\PayDeclareService;
use App\Model\BbcModel\PushAgain;
use Service\PushService\PushYunCangApiService;

class Hnapay extends BaseService
{
    public function reportPay(array $body):array {
        $reportOrder=$body['reportOrder'];
        $payconfig=$body['payconfig'];
        $company=$body['company'];
        $cid=$body['cid'];
        if(empty($reportOrder) || empty($payconfig) || empty($company)){
            return Normal::returnCode(Normal::SUC, '参数缺失,丢弃该条数据');
        }
        //获取回调
        if(isset($body['domain'])&&!empty($body['domain'])){
            $domain=$body['domain'];
            $noticeUrl="{$domain}/paydeclare/notify/hnapay";
        }else{
            $callback_url = PayNotifyService::instance()->getChannelNotifyHost($cid);
            $noticeUrl="http://{$callback_url}/paydeclare/notify/hnapay";
        }
        $receive_info=json_decode($reportOrder[0]['receive_info'],true);
        $report_data=[
            'eportCode'=>(string)$payconfig['ePortCode'],//电子口岸编码
            'merOrderId'=>(string)$body['pay_sn'],
            'currencyCode'=>'CNY',
            'eCompanyCode'=>$company['eCompanyCode'],
            'eCompanyName'=>$company['eCompanyName'],
            'payTransactionNo'=>(string)$body['pay_serial'],
            'actionType'=>'1',
            'payerName' =>$receive_info['buyer']['truename'],
            'payerType' =>'01',
            'payerId'=>$receive_info['buyer']['idcard'],
            'payerPhoneNumber'=>$receive_info['buyer']['mobile']
        ];
        if(count($reportOrder)==1){
            $body['pay_sn'] = $reportOrder[0]['sn'];
            $report_data['noticeUrl']=$noticeUrl;
            OrderReportLog::instance()->add([
                'order_id'=>$reportOrder[0]['id'],
                'sn'=>$body['pay_sn'],
                'content'=>"发起支付单申报",
                'cd'=>time()
            ]);
            $client = (new HnapayApiClient($payconfig));
            $result_call = $client->reportPay($report_data);
            PayReport::instance()->add([
                'order_id'=>$reportOrder[0]['id'],
                'sn'=>$body['pay_sn'],
                'content'=>json_encode($result_call,JSON_UNESCAPED_UNICODE)
            ]);
            if($result_call['data']['content']['responseCode']<>'0000' || $result_call['code']==Normal::FAIL){
                PayDeclareService::instance()->dealDeclareResult($body['pay_sn'], $reportOrder[0]['id'],"支付单申报失败:".$result_call['data']['content']['responseDesc']??''.$result_call['msg']??'',false);
            
            }
            if($reportOrder[0]['need_order_report']==1){
                //TODO订单申报

             }
        }else{
            //拆单申报
            $extendOrder=[];
            foreach ($reportOrder as $v){
                $orderItem['subOrderNo']=$v['sn'];
                $orderItem['payAmount']=(int)(bcmul(round($v['price_order']-$v['points_money'],2),100));
                $goods=OrderGoods::instance()->info(['order_id'=>$v['id'],'_fields_'=>'goods_name,num']);
                $orderItem['goodsName']=$goods['goods_name'];
                $orderItem['goodsCount']=(string)$goods['num'];
                $extendOrder[]=$orderItem;
                $reportOrderData[$v['sn']]=$v;
                OrderReportLog::instance()->add(['order_id'=>$v['id'],'sn'=>$v['sn'],'content'=>"发起支付单申报",'cd'=>time()]);
            }
            $orderSNs= array_column($reportOrder, 'sn');
            $OrderReportStatusList=OrderReportStatus::instance()->lists([['sn','in',$orderSNs]]);
            $OrderReportStatusMapList= array_column($OrderReportStatusList, Null,'sn');
            $subOrderExtends=[
                'OrderReportStatusMapList'  =>$OrderReportStatusMapList,
                'pay_serial_extend'         =>''
            ];
            $report_data['orderDetails']=json_encode($extendOrder);
            $report_data['noticeUrl']=$noticeUrl;
            $client = (new HnapayApiClient($payconfig));
            $result_call = $client->reportPay($report_data);
            PayReport::instance()->add([
                'order_id'=>0,
                'sn'=>$body['pay_sn'],
                'content'=>json_encode($result_call,JSON_UNESCAPED_UNICODE)
            ]);
            if($result_call['data']['content']['responseCode']<>'0000' || $result_call['code']==Normal::FAIL){
                $content="支付单申报失败:".$result_call['data']['content']['responseDesc']??'';
                foreach ($reportOrder as $v){
                    PayDeclareService::instance()->dealDeclareResult($v['sn'], $v['id'], $content,false,$subOrderExtends);
                }
            }
            if(isset($result_call['data']['content']['respOrderDetails'])){
                $idx=array_column($reportOrder,'id','sn');
                $resData=json_decode($result_call['data']['content']['respOrderDetails'],1);
                foreach ($resData as $v){
                    Order::instance()->edit(['sn'=>$v['subOrderNo']],['pay_serial_extend'=>$v['subPayTransactionNo']]);
                    PayReport::instance()->add([
                        'order_id'=>$idx[$v['subOrderNo']],
                        'sn'=>$v['subOrderNo'],
                        'content'=>json_encode($result_call,JSON_UNESCAPED_UNICODE)
                    ]);
                    if($reportOrderData[$v['subOrderNo']]['need_order_report']==1){
                       //TODO订单申报
                    }
                }
            }
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    public function notify(array $body) {
        $msg=$body['msg'];
        $datajson=base64_decode($msg);
        $data= json_decode($datajson,true);
        $sn=isset($data['content']['subOrderNo'])?$data['content']['subOrderNo']:$data['content']['merOrderId'];
          //Db::table('ly_pay_report')->insert(['sn'=>$sn,'notify'=>$datajson]);
        PayReport::instance()->edit(['sn'=>$sn], ['notify'=>$datajson]);
        $order=Order::instance()->info(['sn'=>$sn]);
        $orderStatus=OrderReportStatus::instance()->info(['sn'=>$sn]);
        if(!empty($order)){
            if($data['content']['resultCode']==2){
                $content="支付单申报成功";
                $status=1;
            }else{
                $content="支付单申报失败，".$data['content']['resultMsg'];
                $status=2;
                Order::instance()->edit(['sn'=>$sn],['report_success'=>0]);
            }
            if(!empty($orderStatus)){
                OrderReportStatus::instance()->edit(['id'=>$orderStatus['id']],['pay_report_status'=>$status,'pay_report_time'=>time()]);
            }
            OrderReportLog::instance()->add(['order_id'=>$order['id'],'sn'=>$order['sn'],'content'=>$content,'cd'=>time()]);
            if($status==1){
                $pushagain= PushAgain::instance()->info(['order_id'=>$order['id']]);
                $pushOrder=PushYunCangApiService::instance()->pushYunCangOrderByPushAgain($order['cid'], $pushagain);
                if($pushOrder['code']==Normal::SUC){
                    PushYunCangApiService::instance()->pushYunCangPayByPushAgain($order['cid'], $pushagain);
                }
            }
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
}
